package com.ruoyi.web.controller.activiti;

import com.ruoyi.act.domain.QUERY.ActInitQY;
import com.ruoyi.act.service.ActProcessDefinitionService;
import com.ruoyi.act.domain.VO.DefinitionVO;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @author badcat
 * Date 2021/8/23
 * Time 12:05
 */
@RestController
@RequestMapping("/act/processDefinition")
public class ActProcessDefinitionController {

    @Autowired
    private ActProcessDefinitionService processDefinitionService;

    /**
     * 获取所有最新版本的流程定义，按部署id排序
     * @return
     */
    @PostMapping("/getDefinitions")
    public AjaxResult getDefinitions(Model model){
        List<DefinitionVO> list = this.processDefinitionService.getDefinitions();
        return AjaxResult.success(list);
    }

    /**
     * 读取流程资源
     *
     * @param processDefinitionId 流程定义ID
     * @param resourceName        资源名称
     */
    @GetMapping(value = "/readResource")
    public void readResource(HttpServletResponse response, @RequestParam("pdid") String processDefinitionId, @RequestParam("resourceName") String resourceName)
            throws Exception {

        InputStream inputStream = this.processDefinitionService.readResource(processDefinitionId, resourceName);
        int count = inputStream.available();
        byte[] bytes = new byte[count];
        response.setContentType("text/xml");
        OutputStream outputStream = response.getOutputStream();
        while (inputStream.read(bytes) != -1) {
            outputStream.write(bytes);
        }
        inputStream.close();
    }

    /**
     * 根据文件路径部署流程
     * @return
     */
    @PostMapping("/initDeploymentBPMN")
    public AjaxResult initDeploymentBPMN(@RequestBody ActInitQY initDeploymentBPMNQUERY){
        if(StringUtils.isEmpty(initDeploymentBPMNQUERY.getKey())) initDeploymentBPMNQUERY.setKey(null);
        return processDefinitionService.initDeploymentBPMN(initDeploymentBPMNQUERY.getName(),initDeploymentBPMNQUERY.getStringBPMN(),initDeploymentBPMNQUERY.getKey());
    }

    /**
     * 根据文件路径部署流程
     * @return
     */
    @GetMapping("/delDeploymentBPMN/{id}")
    public AjaxResult delDeploymentBPMN(@PathVariable String id){
        return processDefinitionService.delDeploymentBPMN(id);
    }
}
